package com.ibm.member.common.util;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibm.member.model.BaseBO;
import com.ibm.member.model.MemberBO;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExcelUtil {

    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    @SuppressWarnings("rawtypes")
    public static void toExcel(List list) throws Exception {
        Class clazz = list.get(0).getClass();

        WritableWorkbook book = Workbook.createWorkbook(new File("D:/" + clazz.getSimpleName() + ".xls"));
        WritableSheet sheet = book.createSheet("Sheet1", 0);

        List<Method> methods = new ArrayList<Method>();
        int i = 0;
        for (Method method : clazz.getDeclaredMethods()) {
            String name = method.getName();
            if (name.startsWith("get") && !name.equals("getClass")) {
                methods.add(method);
                sheet.addCell(new Label(i++, 0, name.substring(3, name.length())));
            }
        }
        i = 0;
        for (Object bo : list) {
            int j = 0;
            i++;
            for (Method method : methods) {
                Object obj = method.invoke(bo);
                String value = String.valueOf(obj);
                sheet.addCell(new Label(j++, i, value));
            }
        }
        book.write();
        try {
            book.close();
        } catch (Exception e) {
            log.error("生成Excel出错", e);
        }
    }

    @SuppressWarnings("rawtypes")
    public static void toDatabase(List<BaseBO> list) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        BaseBO bo = new MemberBO("1");
        Class clazz = bo.getClass();
        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get") && !name.equals("getClass")) {
                System.out.println(method.invoke(bo));

            }
        }
    }
}
